<template>
  <el-dialog
    :title="title"
    :visible.sync="isshow"
    width="550px"
    :before-close="cancleAdd"
  >
    <div class="dialogContent">
      <el-form :model="form" ref="form" :rules="rules">
        <el-form-item label="姓名（工号）" label-width="130px" prop="userIds" required>
          <el-cascader
            v-if="updataType==2"
            filterable
            v-model="form.userIds"
            :options="options"
            :props="props"
            collapse-tags
            clearable
            @change="handleSelect"
            style="width: 300px"
          ></el-cascader>
          <div v-else>{{ updateUserName }}（{{ teacherNum }}）</div>
        </el-form-item>
        <el-form-item label="本次可分配容量" label-width="130px" prop="distributable">
          <div>{{ distributableStore }}GB</div>
        </el-form-item>
        <el-form-item label="本次分配容量" label-width="130px" prop="totalStorageSize" required>
          <el-input-number v-model="form.totalStorageSize" :min="1"></el-input-number>
          GB
        </el-form-item>
        <el-form-item label="本次剩余容量" label-width="130px" prop="residue">
          <div :class="residueStore<0?'erroText':''"> {{ residueStore }}GB</div>
          <div v-if="residueStore<0" class="errorTip">剩余容量不足，请重新分配</div>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
    <el-button @click="cancleAdd">取 消</el-button>
    <el-button type="primary" @click="confirmAdd">确 定</el-button>
  </span>
  </el-dialog>
</template>
<script>
import { batchAddStorageConfig, getSchoolconfigInfo, getuserTree } from '@/api/library/librarySet'
import { groupConfigInfo, batchEditStorageConfig } from '@/api/library_groupList/groupList'

export default {
  name: 'storedisposition',
  data() {
    return {
      isshow: false,
      title: '新增',
      type: 'add',
      form: {
        totalStorageSize: 10,
        userIds: [],
        storageIds: []
      },
      props: {
        multiple: true,
        emitPath: false,
        label: 'label',
        value: 'value',
        children: 'children'
      },
      options: [],
      distributableStore: 0,
      rules: {
        userIds: [
          { required: true, message: '请选择用户', trigger: 'change' }
        ],
        totalStorageSize: [
          { required: true, message: '请设置分配容量', trigger: 'blur' }

        ]
      },
      updataType: '2',
      updateUserName: '',
      teacherNum: '',
      rerluserIds: []
    }
  },
  computed: {
    residueStore() {
      return this.form.userIds.length == 0 ? this.distributableStore : this.distributableStore - ((this.form.totalStorageSize || 0) * this.form.userIds.length)
    }
  },
  methods: {
    show(type, arr, updateType) {
      this.type = type
      if (type === 'add') {
        this.title = '新增'
      } else {
        this.title = '存储配置'
        this.updataType = updateType
        this.updateUserName = arr[0].nickName
        this.teacherNum = arr[0].teacherNum
        this.form.userIds = arr.map(e => e.branchIds ? e.branchIds.split(',')[0] + '_' + e.userId : '-1_' + e.userId)
        this.rerluserIds = arr.map(e => e.userId)
        this.form.storageIds = arr.map(e => e.storageId)
        this.form.totalStorageSize = arr.map(e => e.totalStorageSize).reduce((a, b) => a + b, 0)
      }
      this.getUserstoreTree()
      if (type === 'add') {
        this.getSchoolInfo()
      } else {
        this.getGroupInfo(arr.map(e => e.storageId))
      }

      this.isshow = true

    },
    // 确认
    confirmAdd() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.residueStore < 0) {
            this.$message({
              type: 'error',
              message: '容量不足分配，请重新分配！'
            })
            return
          }
          if (this.type === 'add') {
            this.addUserStore()
          } else {
            this.setGroupInfo()
          }
        }
      })
    },
    // 新增
    async addUserStore() {
      let res = await batchAddStorageConfig({
        userIds: this.form.userIds.map(e => e.split('_')[1]),
        totalStorageSize: this.form.totalStorageSize
      })
      if (res.code == 200) {
        this.cancleAdd()
        this.$message.success('新增成功')
        this.$parent.getList()

      }
    },
    // 获取用户树
    async getUserstoreTree() {
      let res = await getuserTree({ dataType: this.type == 'add' ? 1 : 2 })
      if (res.code == 200) {
        this.options = this.handleTeachterData(res.data)
        console.log(this.rerluserIds, '用户树')
      }
    },
    // 处理教师数据，处理为树状结构
    handleTeachterData(data) {
      if (data && data.length > 0) {
        data.forEach(e => {
          e.children = this.handleUserList(e.userList)
          e.id = e.branchId
          e.label = e.branchName
        })
      }
      return data
    },
    handleSelect(data) {
      let arr = data
      let arr2 = []
      if (arr && arr.length > 0) {
        arr.forEach(e => {
          arr2.push((e.split('_')[1]) * 1)
        })
      }
      this.options.forEach(e => {
        e.children.forEach(item => {
          item.disabled = arr2.includes(item.userId) && !arr.includes(item.value)
        })
      })

    },
    handleUserList(arr) {
      arr.forEach(e => {
        e.value = e.branchId ? e.branchId + '_' + e.userId : e.userId
        e.label = e.nickName + '（' + e.userName + '）'
        e.disabled = this.rerluserIds.includes(e.userId) && !this.form.userIds.includes(e.value)
      })
      return arr
    },
    async getGroupInfo(arr) {
      let res = await groupConfigInfo({ storageIds: arr.join(',') })
      if (res.code == 200) {
        this.distributableStore = res.data.remainSize
        this.form.totalStorageSize = res.data.maxAssignedSize
      }
    },
    // 获取学校配置信息
    async getSchoolInfo() {
      let res = await getSchoolconfigInfo({ schoolId: this.$store.getters.schoolId })
      if (res.code == 200) {
        this.distributableStore = res.data.remainSize
      }
    },
    // 修改群组
    async setGroupInfo() {
      let res = await batchEditStorageConfig({
        storageIds: this.form.storageIds,
        totalStorageSize: this.form.totalStorageSize
      })
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: '修改成功！'
        })
        this.cancleAdd()
        this.$message.success('新增成功')
        this.$parent.getList()
      }
    },
    // 取消
    cancleAdd() {
      this.isshow = false
      this.form = {
        totalStorageSize: 10,
        userIds: [],
        storageIds: []
      }
      this.updataType = '2'
      this.$refs['form'].resetFields()
    }

  }
}

</script>


<style scoped lang="scss">
::v-deep .el-cascader.el-cascader--medium {
  width: 230px;
}

.errorTip {
  color: red;
  font-size: 12px;
}

.erroText {
  color: red;
}
</style>
